import {
	spinSpecSheetAudit, spinSpecSheetClearAudit, spinSpecSheetClearClose,
	spinSpecSheetClearSubmitAudit, spinSpecSheetClose,
	spinSpecSheetCreate,
	spinSpecSheetGet,
	spinSpecSheetUpdate,
	spinSpecSheetUpdateAudit, spinSpecSheetUpdateAuditState
} from '../../../../../api/technology/order';
import { spinProcessPage } from '../../../../../api/technology/process';
import { spinMachineModelPage } from '../../../../../api/basicData/machineModel';
import { spinSpecParamPage } from '../../../../../api/technology/item';
import handlerCache from '../../../../../mixins/handler-cache';
import remoteSearchBatchCodeInput from '../../../../production/qhPrd/productConfigCotton/components/remote-search-batch-code-input';
import { spinSpecSheetTaskGet } from '../../../../../api/production/xsNotice';
import { formatDate } from '../../../../../utils/jk/jk-tool';
import jkSaveButton from '../../../../jk-components/jk-save-button';
import jkUpdateButton from '../../../../jk-components/jk-update-button';
import remoteSearchEmpInput from '../../../../technology/order/components/remote-search-emp-input';
let _this = null;
export default {
	components: { jkSaveButton, jkUpdateButton, remoteSearchEmpInput, remoteSearchBatchCodeInput },
	mixins: [handlerCache],
	props: {
		pageType: {
			type: String,
			default: 'add'
		}
	},
	data() {
		const validateGm = (rules, value, callback) => {
			if (value && _this.ruleForm.gramWeight && _this.ruleForm.meters) {
				return callback();
			} else {
				return callback(new Error());
			}
		};
		return {
			prefix: 'spin:specSheet',
			dataId: null,
			apiItem: {
				'save': spinSpecSheetCreate,
				'enable': spinSpecSheetUpdateAuditState,
				'update': spinSpecSheetUpdate,
				'updateAudit': spinSpecSheetUpdateAudit,
				'submit': spinSpecSheetUpdate, // 后端暂时没有'保存并提交接口'，先用update代替
				'cancelSubmit': spinSpecSheetClearSubmitAudit,
				'submitAudit': spinSpecSheetUpdateAudit,
				'audit': spinSpecSheetAudit,
				'cancelAudit': spinSpecSheetClearAudit,
				'close': spinSpecSheetClose,
				'cancelClose': spinSpecSheetClearClose
			},
			tableData1: [
				{
					typeName: '未打卡',
					postName: '机修工',
					empList: [{}, {}, {}]
				},
				{
					typeName: '迟到早退',
					postName: '机修工',
					empList: [{}, {}, {}]
				},
				{
					typeName: '未打卡',
					postName: '细纱挡车工',
					empList: [{}, {}, {}]
				},
				{
					typeName: '迟到早退',
					postName: '细纱挡车工',
					empList: [{}, {}, {}]
				},
				{
					typeName: '请假',
					postName: '细纱挡车工',
					empList: [{}, {}, {}]
				},
				{
					typeName: '未打卡',
					postName: '梳棉挡车工',
					empList: [{}, {}, {}]
				},
				{
					typeName: '迟到早退',
					postName: '梳棉挡车工',
					empList: [{}, {}, {}]
				},
				{
					typeName: '请假',
					postName: '梳棉挡车工',
					empList: [{}, {}, {}]
				}
			],
			tableData: [],
			tableLoading: false,
			processList: [],
			updateAuditLoading: false,
			auditStateLoading: false,
			saveBtnLoading: false,
			saveAndEnableBtnLoading: false,
			workshopList: [],
			showLoading: true,
			saveDialogState: false,
			machineModelList: [],
			ruleForm: {
				'code': '编号自动生成',
				'batchCode': '',
				'dailyYield': null,
				'efficiencyPercent': null,
				'fixedLength': null,
				'gramWeight': null,
				'machineModelCode': '',
				'machineModelId': null,
				'machineModelName': '',
				'meters': null,
				'moistureRegain': null,
				'numbers': null,
				'processCode': '',
				'processId': null,
				'processName': '',
				'productCode': '',
				'productId': null,
				'productModels': '',
				'productName': '',
				'specDate': '',
				'specEmpId': null,
				'specEmpName': ''
			},
			rules: {
				gramWeight: [{ required: true, validator: validateGm, trigger: 'change' }],
				meters: [{ required: true, trigger: 'change' }],
				moistureRegain: [{ required: true, trigger: 'change' }],
				fixedLength: [{ required: true, trigger: 'change' }],
				efficiencyPercent: [{ required: true, trigger: 'change' }],
				dailyYield: [{ required: true, trigger: 'change' }],
				specEmpId: [{ required: true, trigger: 'change' }],
				productId: [{ required: true, trigger: 'change' }],
				machineModelId: [{ required: true, trigger: 'change' }],
				batchCode: [{ required: true, trigger: 'change' }],
				processId: [{ required: true, trigger: 'change' }],
				code: [{ required: true, trigger: 'change' }],
				name: [{ required: true, trigger: 'change' }]
			}
		};
	},
	methods: {
		mergeColMethod({ row, _rowIndex, column, visibleData }) {
			const fields = ['postName']; // 根据字段判断数据相同的合并
			const cellValue = row[column.property];
			if (cellValue && fields.includes(column.property)) {
				const prevRow = visibleData[_rowIndex - 1];
				let nextRow = visibleData[_rowIndex + 1];
				if (prevRow && prevRow[column.property] === cellValue) {
					return { rowspan: 0, colspan: 0 };
				} else {
					let countRowspan = 1;
					while (nextRow && nextRow[column.property] === cellValue) {
						nextRow = visibleData[++countRowspan + _rowIndex];
					}
					if (countRowspan > 1) {
						return { rowspan: countRowspan, colspan: 1 };
					}
				}
			}
		},
		onEditBtn() {
			this.$toOtherRouter({
				name: 'editTechnology',
				query: {
					id: this.$route.query.id ? Number(this.$route.query.id) : null
				}
			});
		},
		async getDependentData() {
			this.showLoading = true;
			this.dataId = this.$route.query.id ? Number(this.$route.query.id) : null;
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
			});
			// 详情页不请求依赖的接口
			if (this.pageType !== 'detail') {
				await this.getMachineModelListRequest();
				await this.getProcessListRequest();
			}
			// 新增页
			if (this.pageType === 'add') {
				this.$set(this.ruleForm, 'specDate', formatDate(Date.now()));
				this.$set(this.ruleForm, 'specEmpId', this.$store.state.user.empInfo.id);
				this.$set(this.ruleForm, 'specEmpName', this.$store.state.user.empInfo.name);
				// 来源工艺任务时
				if (this.$route.query.technologyTaskId) {
					await this.getTechnologyTaskDetailRequest(this.$route.query.technologyTaskId).then(res => {
						if (res.data.status === 200) {
							const resData = res.data.res;
							this.$set(this.ruleForm, 'productId', resData.productId);
							this.$set(this.ruleForm, 'productCode', resData.productCode);
							this.$set(this.ruleForm, 'productName', resData.productName);
							this.$set(this.ruleForm, 'productModels', resData.productModels);
							this.$set(this.ruleForm, 'batchId', resData.batchId);
							this.$set(this.ruleForm, 'batchCode', resData.batchCode);
							const processItem = this.processList.find(x => x.code.toUpperCase() === (resData.prdNotice.processCode ? resData.prdNotice.processCode : 'XS').toUpperCase());
							this.$set(this.ruleForm, 'processId', processItem.id);
							this.$set(this.ruleForm, 'processCode', processItem.code);
							this.$set(this.ruleForm, 'processName', processItem.name);
						}
					});
				}
			}
			// 详情页不请求依赖的接口
			if (this.pageType !== 'detail') await this.getTechnologyItemListRequest();
			if (this.dataId) await this.getDetailRequest();
			this.showLoading = false;
		},
		setDependentDataOfForm() {
			const params = JSON.parse(JSON.stringify(this.ruleForm));
			params.processCode = this.processList.find(x => x.id === params.processId).code;
			params.processName = this.processList.find(x => x.id === params.processId).name;
			params.machineModelCode = this.machineModelList.find(x => x.id === params.machineModelId).code;
			params.machineModelName = this.machineModelList.find(x => x.id === params.machineModelId).name;
			params.specSheetParamList = JSON.parse(JSON.stringify(this.tableData));
			return params;
		},
		onProcessChange() {
			this.tableData = [];
			/* this.$set(this.ruleForm, 'batchCodeId', null);
			this.$set(this.ruleForm, 'batchCode', null);
			this.$set(this.ruleForm, 'productId', null);
			this.$set(this.ruleForm, 'productCode', null);
			this.$set(this.ruleForm, 'productName', null);*/
			this.getTechnologyItemListRequest();
		},
		onSelectBatchCodeChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'batchCode', e.batchCode);
			}
		},
		onSelectEmpChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'specEmpId', e.id);
				this.$set(this.ruleForm, 'specEmpCode', e.code);
				this.$set(this.ruleForm, 'specEmpName', e.name);
			}
		},
		onSelectProductChange(e) {
			if (Object.keys(e).length) {
				this.setProductDependentData(e);
			}
		},
		setProductDependentData(e) {
			this.$set(this.ruleForm, 'batchCodeId', null);
			this.$set(this.ruleForm, 'batchCode', '');
			this.$set(this.ruleForm, 'productId', e.id);
			this.$set(this.ruleForm, 'productCode', e.code);
			this.$set(this.ruleForm, 'productName', e.name);
			this.$set(this.ruleForm, 'productModels', e.models);
		},
		defaultRowData() {
			return {
				processId: null,
				processCode: '',
				processName: ''
			};
		},
		getParamData() {
			const params = JSON.parse(JSON.stringify(this.ruleForm));
			params.processCode = this.processList.find(x => x.id === params.processId).code;
			params.processName = this.processList.find(x => x.id === params.processId).name;
			params.specSheetParamList = JSON.parse(JSON.stringify(this.tableData));

			const modelItem = this.machineModelList.find(x => x.id === params.machineModelId) || {};
			params.machineModelCode = modelItem.code;
			params.machineModelName = modelItem.name;
			return params;
		},
		onConfirmBtn(type) {
			this.$refs['ruleForm'].validate(valid => {
				if (valid) {
					this.saveRequest(type);
				} else {
					this.$tipsBar(this, 'validator');
				}
			});
		},
		saveRequest(type) {
			if (type === 2) {
				this.saveAndEnableBtnLoading = true;
			} else {
				this.saveBtnLoading = true;
			}
			// 新增
			if (!this.dataId) {
				this.ruleForm.id = null;
				this.apiItem.save(this.getParamData()).then(res => {
					this.saveBtnLoading = false;
					this.saveAndEnableBtnLoading = false;
					if (res.data.status === 200) {
						this.dataId = res.data.res;
						if (type === 2) {
							this.enableRequest(this.dataId).then(res => {
								if (res.data.status === 200) {
									this.$tipsBar(this, 'save');
									this.onJump(this.dataId);
								}
							});
						} else {
							this.$tipsBar(this, 'save');
							this.onJump(res.data.res);
						}
					}
				});
				return;
			}
			// 编辑
			this.apiItem.update(this.getParamData()).then(res => {
				this.saveBtnLoading = false;
				this.saveAndEnableBtnLoading = false;
				if (res.data.status === 200) {
					if (type === 2) {
						this.enableRequest(this.dataId).then(res => {
							if (res.data.status === 200) {
								this.$tipsBar(this, 'save');
								this.getDependentData();
							}
						});
					} else {
						this.$tipsBar(this, 'save');
						this.getDependentData();
					}
				}
			});
		},
		onAuditStateChange() {
			this.auditStateLoading = true;
			this.enableRequest(this.dataId).then(res => {
				this.auditStateLoading = false;
				if (res.data.status === 200) {
					this.getDependentData();
				}
			});
		},
		enableRequest(id) {
			return spinSpecSheetUpdateAuditState({ id });
		},
		onVisibleChange(e) {
			this.$emit('on-visible-change', e);
			if (!e) {
				Object.assign(this.$data, this.$options.data());
				this.$nextTick(() => {
					this.$refs.ruleForm.resetFields();
				});
			}
		},
		getDetailRequest() {
			return spinSpecSheetGet({ id: this.dataId }).then(res => {
				this.showLoading = false;
				if (res.data.status === 200) {
					const resData = JSON.parse(JSON.stringify(res.data.res));
					delete resData.specSheetParamList;
					this.ruleForm = resData;
					this.tableData = res.data.res.specSheetParamList.map(x => {
						x.val = x.dataType === 1 ? Number(x.val) : x.val;
						x.valMax = x.dataType === 1 ? Number(x.valMax) : x.valMax;
						x.valMin = x.dataType === 1 ? Number(x.valMin) : x.valMin;
						return x;
					});
				}
			});
		},
		getProcessListRequest() {
			return spinProcessPage({ auditState: 1 }).then(res => {
				if (res.data.status === 200) {
					this.processList = res.data.res;
				}
			});
		},
		getMachineModelListRequest() {
			return spinMachineModelPage({ auditState: 1 }).then(res => {
				if (res.data.status === 200) {
					this.machineModelList = res.data.res;
				}
			});
		},
		getTechnologyItemListRequest() {
			if (!this.ruleForm.processId) return;
			/* return spinSpecParamPage({ auditState: 1, processId: this.ruleForm.processId }).then(res => {
				if (res.data.status === 200) {
					this.tableData = res.data.res.map(x => {
						return {
							dataType: x.dataType,
							specParamId: x.id,
							ifBusi: x.ifBusi,
							ifNull: x.ifNull,
							ifWarning: x.ifWarning,
							iotIdentifier: x.iotIdentifier,
							specParamCode: x.code,
							specParamName: x.name,
							paramType: x.paramType,
							val: null,
							valMax: null,
							valMin: null
						};
					});
				}
			});*/
		},
		// 获取工艺任务的详情
		getTechnologyTaskDetailRequest(id) {
			return spinSpecSheetTaskGet({ id });
		},
		onJump(id) {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toOtherRouter({
				name: 'editTechnology',
				query: { id }
			});
		},
		onJumpList() {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toMainRouter({
				name: 'TechnologyOrder'
			});
		},
		clearCacheMethod() {
			// Object.assign(this.$data, this.$options.data());
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
				this.getDependentData();
			});
		}
	},
	mounted() {
		_this = this;
	}
};
